import { Form } from 'antd';
import React from 'react';
import { ModalForm } from '@ant-design/pro-form';

// 编辑页面公用的props与用来关闭的回调函数
import { onVisibleChangeHandle } from '@/services/Common';
import { useModel } from 'umi';
import { getCurrentAdminGroup, getAdminGroupTree } from '@/services/system/admin';
import { convertToTreeData, getShortcutJson } from './utils';
import { saveShortcutToStore } from '@/layouts/nested/SubSider/utils';
import type { DataNode } from 'rc-tree/lib/interface';

// 从本地缓存中得到用逗号分割的快捷菜单字符串
import { getShortcutForTree } from '@/layouts/nested/SubSider/utils';
import { saveShortcut } from '@/services/user';

import TreeTransfer from './TreeTransfer';

type ShortcutSettingProps = {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  listReload: () => void;
};

const ShortcutSetting: React.FC<ShortcutSettingProps> = (props: ShortcutSettingProps) => {
  const { visible, setVisible, listReload } = props;
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');

  // 待选的菜单
  const [treeData, setTreeData] = React.useState<DataNode[]>([]);

  // 已经选中的内容
  const [targetKeys, setTargetKeys] = React.useState<string[]>([]);

  // 读取取数据库中的数据，并刷新页面
  React.useEffect(() => {
    // 待选的菜单列表
    if (initialState?.currentUser) {
      if (initialState?.currentUser.user.adminIsSuper) {
        getAdminGroupTree().then((result) => {
          if (result.data) {
            setTreeData(convertToTreeData(result.data));
          }
        });
      } else {
        getCurrentAdminGroup().then((result) => {
          if (result.data) {
            const resultObject = JSON.parse(result.data.limits || '');
            setTreeData(convertToTreeData(resultObject));
          }
        });
      }
    }
    // 读取已经选中的菜单列表，作为快捷菜单
    setTargetKeys(getShortcutForTree());
  }, []);

  /**
   *  点击保存按钮时，触发的事件
   */
  const onFinishHandle = async () => {
    // 要组装一个可以保存到本地存储的内容
    const saveData = getShortcutJson(targetKeys, treeData);
    let strTemp: string = '';
    if (saveData.length > 0) {
      strTemp = JSON.stringify(saveData);
    }
    // 保存到数据库中
    await saveShortcut(strTemp);
    // 保存到本地缓存中
    saveShortcutToStore(saveData);
    // 刷新当前窗口
    listReload();
    return true;
  };

  /**
   * 穿梭组件的onChange事件
   */
  const onChange = (keys: string[]) => {
    setTargetKeys(keys);
  };

  return (
    <ModalForm
      form={form}
      title="设置快捷菜单"
      visible={visible}
      onVisibleChange={(visibleProp) => onVisibleChangeHandle(visibleProp, setVisible)}
      onFinish={onFinishHandle}
    >
      <TreeTransfer dataSource={treeData} targetKeys={targetKeys} onChange={onChange} />
    </ModalForm>
  );
};
export default ShortcutSetting;
